﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;  //使用注册表需要此行
using System.Runtime.InteropServices;   //使用外部api定义时用DllImport
using System.Threading;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using WeiXin.WeChatData;
using Newtonsoft.Json;
using System.Timers;
using System.Text.RegularExpressions;
using System.Data.SQLite;
using System.IO;

namespace WeiXin
{
    public partial class FormMain : Form
    {
        static AppServer appServer { get; set; }
        private static ChatRoom CurrentRoom { get; set; }
        // private static string JavaIP { get; set; }
        private static string sharedGroupId = null;
        public FormMain()
        {
            InitializeComponent();
            //m_SyncContext = SynchronizationContext.Current;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string info = "";
            RegistryKey key = Registry.CurrentUser;
            RegistryKey software = key.OpenSubKey("Software\\Tencent\\WeChat", true);
            info = software.GetValue("InstallPath").ToString();
            weixinpath.Text = info + "\\WeChat.exe";

        }

        public class common // 定义全局变量
        {
            public static string text;
            public static int 微信句柄;
            public static int pid;
        }

        public static IntPtr LoginOk = (IntPtr)0x1000BB;
        /// 消息主要接受程序
        /// </summary>
        /// <param name="m"></param>
        protected override void DefWndProc(ref Message m)
        {

            switch (m.Msg)
            {
                case 74:
                    string message = "";
                    int f = (int)m.WParam;
                    try
                    {
                        COPYDATASTRUCT2 cds2 = (COPYDATASTRUCT2)m.GetLParam(typeof(COPYDATASTRUCT2));
                        message = Marshal.PtrToStringAnsi(cds2.lpData);

                    }
                    catch (Exception e)
                    {
                        LogHelper.WriteLog("解析微信消息报错", e);  //发文字带空格报错
                    }

                    switch (f)
                    {
                        case 10001:
                            Int32.TryParse(message, out common.微信句柄);
                            break;
                        case 10002:
                            Int32.TryParse(message, out common.微信句柄);
                            break;
                        case 10005:  //微信退出
                            LogHelper.WriteLog(Convert.ToString(f) + "|| 微信退出登录" + "||" + message);
                            break;
                        //登录时解析用户信息
                        case 10003:
                            try
                            {
                                Thread.Sleep(200);
                                LogHelper.WriteLog(Convert.ToString(f) + "|| 微信登录成功" + "||" + message);
                                if (!string.IsNullOrEmpty(message))
                                {
                                    //ThreadPool.QueueUserWorkItem(new WaitCallback(MessageHandler.Parse10003), message);
                                    MessageHandler.Parse10003(message);
                                }

                                this.Invoke(new MethodInvoker(() => { richTextBox1.AppendText("【" + MessageHandler.myUserInfo.UserName + "】登录成功!\r\n"); }));
                            }
                            catch (Exception e1)
                            {
                                LogHelper.WriteLog("解析微信登录用户信息错误", e1);
                            }
                            return;
                        //登录时获取用户群组
                        case 10006:
                            try
                            {
                                Thread.Sleep(200);
                                LogHelper.WriteLog(Convert.ToString(f) + "||" + message);
                                if (!string.IsNullOrEmpty(message))
                                {
                                    ThreadPool.QueueUserWorkItem(new WaitCallback(MessageHandler.Parse10006), message);
                                }
                            }
                            catch (Exception e2)
                            {
                                LogHelper.WriteLog("解析微信群信息错误", e2);
                            }
                            break;

                        //文字,图片,视频,文件 解析
                        case 10012:
                            try
                            {
                                if (message.Contains("msgtyp:"))
                                {
                                    string[] datas = Regex.Split(message, "msgtyp:", RegexOptions.IgnoreCase);
                                    if (datas.Count() >= 2)
                                    {
                                        string msgtyp = datas[1].Split(',')[0];
                                        switch (msgtyp.Replace(" ", ""))
                                        {
                                            case "1":  //文字

                                                if (message.Contains("[群-->]") && message.Contains("[消息内容-->]"))
                                                {
                                                    string word = "";      //发送内容

                                                    //取消息内容
                                                    string[] wordArr = Regex.Split(message, @"消息内容-->]", RegexOptions.IgnoreCase);

                                                    string[] aa = wordArr[1].Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
                                                    if (aa[0].StartsWith(" "))
                                                    {
                                                        word = aa[0].Substring(1);
                                                    }
                                                    else
                                                    {
                                                        word = aa[0];
                                                    }

                                                    string groupId = WxMessageHelper.GetChatRoom(message);
                                                    sharedGroupId = groupId;
                                                    string groupName = WxMessageHelper.GetGroupName(message);
                                                    string nickName = WxMessageHelper.GetNickName(message);
                                                    string memberpuid = WxMessageHelper.GetWxId(message);

                                                    IDictionary<string, string> data = ReadFile();
                                                    foreach (var kv in data)
                                                    {
                                                        string key = kv.Key;
                                                        string value = kv.Value;
                                                        string str = @"{key}:{value}";
                                                        if (word.Contains(key))
                                                        {
                                                            string[] sarr = Regex.Split(word, str, RegexOptions.IgnoreCase);

                                                            this.Invoke(new MethodInvoker(() =>
                                                            {
                                                                if (sarr.Length > 0)
                                                                {
                                                                    richTextBox1.AppendText("【" + nickName + "】在【" + groupName + "】发送了关键词消息：" + sarr[0]);
                                                                }
                                                                richTextBox1.AppendTextColorful(key, Color.Red, false);
                                                                richTextBox1.AppendText(key + "\r\n");
                                                            }));

                                                            //调用回复
                                                            SendMessage(groupId + "||" + value, 20001);
                                                        }
                                                    }
                                                }

                                                break;
                                            case "3":   //image
                                                break;
                                            case "51":  //退出群
                                                LogHelper.WriteLog("点击群或退群记录:" + message);
                                                break;
                                            case "10000": //邀请人进群
                                                LogHelper.WriteLog("邀请入群信息:" + message);
                                                break;
                                            default:
                                                LogHelper.WriteLog("其它类型消息:" + message);
                                                break;
                                        }
                                    }
                                }
                            }
                            catch (Exception e2)
                            {
                                this.Invoke(new MethodInvoker(() => { richTextBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "10012 : 解析微信群信息错误\r\n\r\n"); }));
                                LogHelper.WriteLog("解析微信群信息错误", e2);
                            }
                            break;
                        default:
                            Thread.Sleep(200);
                            break;
                    }
                    //消息内容  cds.lpData
                    break;

                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        //private static unsafe byte[] ReadBytes(IntPtr data)
        //{
        //    var result = new List<byte>();
        //    for (var p = (byte*)data; *p != 0; p++)
        //    {
        //        result.Add(*p);
        //    }
        //    return result.ToArray();
        //}

        private IDictionary<string, string> ReadFile()
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (File.Exists(FormSet.fileName))
            {
                DataTable dt = new DataTable();
                dt.TableName = "TableName";
                dt.Columns.Add("关键字", Type.GetType("System.String"));
                dt.Columns.Add("回复内容", Type.GetType("System.String"));
                dt.ReadXml(FormSet.fileName);
                foreach (DataRow dr in dt.Rows)
                {
                    string key = dr["关键字"].ToString();
                    string val = dr["回复内容"].ToString();
                    LogHelper.WriteLog($"读取了{key}:{val}");

                    if (!result.ContainsKey(key))
                    {
                        result.Add(key, val);
                    }
                }
            }
            return result;

        }

        //private List<string> ReadFile()
        //{
        //    List<string> list = new List<string>();

        //    if (!File.Exists(@"file\data.txt"))
        //    {
        //        File.Create(@"file\data.txt").Close();
        //    }

        //    using (StreamReader sr = File.OpenText(@"file\data.txt"))
        //    {
        //        while (sr.Peek() != -1)
        //        {
        //            string temp = sr.ReadLine().ToString();
        //            list.Add(temp);
        //        }
        //    }

        //    return list;
        //}

        ///////接收
        private void button1_Click(object sender, EventArgs e)
        {
            if (weixinpath.Text != "")
            {
                process1.StartInfo.FileName = weixinpath.Text;
                process1.Start();
                common.pid = process1.Id;
                this.Text = "HCWeChatWinForPC";
                LogHelper.WriteLog("PC微信程序启动....");
            }
        }

        public void SetMsg(string str)
        {
            //textBox_Message.Invoke(new Action(()=>
            //{
            //    this.Text += str;
            //}));
            IntPtr i = this.Handle;
            richTextBox1.BeginInvoke(new Action(() =>
            {
                richTextBox1.Text += str;
            }));
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="wParam">通讯号</param>
        /// <returns></returns>
        private int SendMessage(string message, int wParam)
        {
            byte[] sarr = System.Text.Encoding.Default.GetBytes(message);
            int len = sarr.Length;
            COPYDATASTRUCT cds;
            cds.dwData = (IntPtr)Convert.ToInt16(1);    //可以是任意值
            cds.cbData = len + 1;   //指定lpData内存区域的字节数
            cds.lpData = message;  //发送给目标窗口所在进程的数据
            return myapi.SendMessage(common.微信句柄, 74, wParam, ref cds);  //74代表WM_COPYDATA
        }


        //查找群
        private void button6_Click(object sender, EventArgs e)
        {

        }
        //获取好友列表
        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (appServer != null)
                //Stop the appServer
                appServer.Stop();
        }



        private void timer3_Tick(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            FormSet f2 = new FormSet();
            f2.ShowDialog();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (!isWithinValidHours())
            {
                this.timerSend.Enabled = false;
                return;
            }
            try
            {
                //在这里把界面上textbox的内容赋值sharedGroupId即可
                if (sharedGroupId == null)
                    return;
                var dic = ReadFile();
                string key = "@机器人";
                if (!dic.ContainsKey(key))
                    return;
                LogHelper.WriteLog("触发定时发送");

                //调用回复
                SendMessage(sharedGroupId + "||" + dic[key], 20001);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("定时发送错误", ex);  //发文字带空格报错
            }

        }
        ToolTip toolTip1 = new ToolTip();
        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            toolTip1.SetToolTip(trackBar1, trackBar1.Value.ToString());
            this.timerSend.Interval = trackBar1.Value * 1000;
        }

        private bool isWithinValidHours()
        {
            return DateTime.Now.TimeOfDay > new TimeSpan(10, 30, 0)
                && DateTime.Now.TimeOfDay < new TimeSpan(22, 30, 0);
        }

        private void chkTimerSwitch_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkTimerSwitch.Checked)
            {
                if (isWithinValidHours())
                {
                    this.timerSend.Enabled = true;
                    this.lblTimerSwitch.Text = "定时开启";
                }
                else
                {
                    this.chkTimerSwitch.Checked = false;
                }
            }
            else
            {
                this.timerSend.Enabled = false;
                this.lblTimerSwitch.Text = "定时关闭";
            }
        }
    }



}

